package com.huluobo.mvidemo.news

import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.gson.Gson
import com.huluobo.mvidemo.entity.NewsBean
import com.huluobo.mvidemo.entity.NewsBeanItem
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

/**
 *  Created by LC on 2025/1/13.
 */

@Composable
fun NewsPage(vm: NewsViewModel = hiltViewModel()) {
    //保存数据的状态
    val list = remember {
        SnapshotStateList<NewsBeanItem>()
    }

    //开启协程,准备发起请求
    LaunchedEffect(key1 = "", block = {
        //协程中,当接收到状态的变化时,需要改变数据,或者进行页面的其他操作
        //相当于观察数据变化
        launch {
            vm.state.collect {
                when (it) {
                    is NewsState.onError -> {
                        Log.i("TagA", "error:${it.msg}")
                    }

                    NewsState.onLoading -> {
                    }

                    is NewsState.onSuccess -> {
                        val data = Gson().fromJson(it.data.values, NewsBean::class.java)
                        list.addAll(data)
                    }
                }
            }
        }

        //发起请求的协程
        launch {
            val map = mutableMapOf<String, Int>()
            map["page"] = 0
            val json = Gson().toJson(map)
            val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), json)
            vm.channel.send(NewsIntent.getNews(body))
        }
    })

    //布局
    LazyColumn(content = {
        items(list) {
            Column {
                Text(text = "新闻标题:${it.newsTitle}")
                Text(text = "新闻内容:${it.newsValue}")
            }
        }
    })
}